#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import string

import tornado
import tornado.web
import datetime
import os
import re
from utils import log
import json
from config import etc
from controls import mongo
from controls import data_user_base_mysql
from controls import data_user_brief_mysql
from controls import data_user_detail_mysql
from controls import data_user_ss_mysql
from controls import data_img_base_mysql
# from controls import data_user_head_mysql
from controls import data_topic_note_mysql
from controls import data_topic_note_like_mysql
from controls import data_user_third_mysql
from controls import data_black_user_mysql
from utils import fdfs
from PIL import Image
import tempfile
from utils import util
from utils import file_util
from utils import session_base
from utils.reg_expressions import mail_regex, phone_regex
from utils.session_base import ApiGuest, ApiHost
from utils.session_mc import BaseHandler, login, logout
from utils.sms_util import yunpian_send_sms, generate_verify_code
from utils.verify_code import save_verify_code, check_verify_code, VERIFY_TYPE_FIND, VERIFY_TYPE_REGISTER, \
    del_verify_code


class TestHandler(BaseHandler):
    def get(self):
        return self.redirect('http://static.shitouren.com/group1/M00/00/00/0g6asVUlhsGAH4NTAAfYzBjHljI331_big.jpg',
                             permanent=True)

    def post(self, filename):
        print('i download file handler : ', filename)
        # Content-Type这里我写的时候是固定的了，也可以根据实际情况传值进来
        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Disposition', 'attachment; filename=' + filename)
        # 读取的模式需要根据实际情况进行修改
        with open(filename, 'rb') as f:
            while True:
                data = f.read(buf_size)
                if not data:
                    break
                self.write(data)
        # 记得有finish哦
        self.finish()


class FileHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('''
                <html>
                <head><title>Upload File</title></head>
                <body>
                <form action='file' enctype="multipart/form-data" method='post'>
                <input type='file' name='file'/><br/>
                <input type='submit' value='submit'/>
                </form>
                </body>
                </html>
            ''')

    def post(self):
        upload_path = os.path.join(os.path.dirname(etc.path_img), '')
        file_metas = self.request.files['file']
        for meta in file_metas:
            raw_name = meta['filename']
            imgid = mongo.count_imgid()
            if not imgid:
                log.e('imgid fetching error')
                self.write('failed')
                self.finish()
                return
            ext_name = raw_name.split('.').pop()
            prefix_name_300 = '_300'
            prefix_name_100 = '_100'
            dst_name = str(imgid) + '.' + ext_name
            thb_name_300 = str(imgid) + prefix_name_300 + '.' + ext_name
            thb_name_100 = str(imgid) + prefix_name_100 + '.' + ext_name
            if ext_name == raw_name:
                ext_name = ''
                dst_name = str(imgid)
                thb_name_300 = str(imgid) + prefix_name_300
                thb_name_100 = str(imgid) + prefix_name_100
            dst_path = os.path.join(upload_path, dst_name)
            thb_path_300 = os.path.join(upload_path, thb_name_300)
            thb_path_100 = os.path.join(upload_path, thb_name_100)
            # 有些文件需要已二进制的形式存储，实际中可以更改
            with open(dst_path, 'wb') as up:
                up.write(meta['body'])
            tf = tempfile.NamedTemporaryFile()
            tf.write(meta['body'])
            tf.seek(0)
            # create 300 thumb file
            img_300 = Image.open(dst_path)
            img_size = img_300.size
            pix_x, pix_y = util.get_img_pixs(300, img_size[0], img_size[1])
            # log.i('x:'+str(pix_x) +', y:' +str(pix_y))
            img_300.thumbnail((pix_x, pix_y), resample=1)
            img_300.save(thb_path_300)
            img_300.thumbnail((pix_x / 3, pix_y / 3), resample=1)
            img_300.save(thb_path_100)
            tf.close()
            dst_res = fdfs.upload_file(imgid, dst_path, ext_name)
            if not dst_res:
                pass
            thb_res = fdfs.upload_slave_file(imgid, dst_res['file_id'], thb_path_300, prefix_name_300, ext_name)
            if not thb_res:
                pass
            thb_res_100 = fdfs.upload_slave_file(imgid, dst_res['file_id'], thb_path_100, prefix_name_100, ext_name)
            if not thb_res_100:
                pass
            if dst_res:
                dst_res['sizetype'] = 1
            if data_img_base_mysql.add_img_base_item(dst_res):
                self.write(json.dumps(dst_res) + '\n' + json.dumps(thb_res) + '\n' + json.dumps(thb_res_100))
                self.finish()
                return
        log.e('error')
        self.write('failed')
        self.finish()
        return


class SendCodeHandler(BaseHandler):
    @ApiGuest
    def post(self):
        phone = self.ss_params['phone']
        v_type = self.ss_params['type']
        log.i('phone=%s, ssid=%s' % (phone, self.ssid))
        if not phone:
            log.w('empty phone')
            res = {'idx': self.ss_idx, 'ret': 2, 'msg': '手机号不能为空', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        phone = phone.strip()
        rephone = re.compile(phone_regex)
        if not rephone.match(phone):
            log.w('phone verify failed')
            res = {'idx': self.ss_idx, 'ret': 3, 'msg': '手机号格式有误', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        if v_type == 'register' \
                and data_user_base_mysql.get_user_base_by_phone(phone):
            log.i('phone has been used')
            res = {'idx': self.ss_idx, 'ret': 4, 'msg': '该手机号已被注册', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        # verify = ''.join(random.sample(string.ascii_letters + string.digits, 4))
        verify = generate_verify_code()
        log.i('send code phone=%s, code=%s' % (phone, verify))
        # TODO：send in queue
        ret = yunpian_send_sms(phone, verify)
        if not ret:
            log.i('send sms failed')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': '发送验证码失败', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        # one phone, one verify
        save_verify_code(phone, v_type, verify)

        res = {'idx': self.ss_idx, 'ret': 0, 'msg': '发送验证码成功', 'res': {}}
        self.write(json.dumps(res))
        self.finish()
        return


class SignInHandler(BaseHandler):
    @ApiGuest
    def post(self):
        """
        signin from anywhere, include phone, weixin and others
        'ret': 1, 未绑定
        :return:
        """
        from_where = self.ss_params['from']

        if from_where == 'phone':
            # phone and pwd
            phone = self.ss_params['phone']
            passwd = self.ss_params['passwd']

            phone = phone.strip()
            log.i('phone=%s , passwd=%s' % (phone, passwd))
            if not phone or not passwd:
                log.w('empty phone or passwd')
                res = {'idx': self.ss_idx, 'ret': 2, 'msg': '手机号和密码不能为空', 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return

            rephone = re.compile(phone_regex)
            if not rephone.match(phone):
                log.w('phone verify failed')
                res = {'idx': self.ss_idx, 'ret': 3, 'msg': '手机号格式有误', 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return
            user_base = data_user_base_mysql.get_user_base_by_phone(phone)
            if not user_base:
                log.i('no such user')
                res = {'idx': self.ss_idx, 'ret': 4, 'msg': '手机号或密码错误', 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return
            if passwd != user_base['passwd']:
                log.i('passwd err ' + user_base['passwd'])
                res = {'idx': self.ss_idx, 'ret': 5, 'msg': '手机号或密码错误', 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return
        else:
            unionid = self.ss_params['unionid']
            user_third = data_user_third_mysql \
                .get_user_third_by_type_and_userkey(from_where, unionid)

            if not user_third:
                ret = {
                    'idx': self.ss_idx,
                    'ret': 0,
                    'res': {'phone': ''},
                    'msg': '未绑定手机号',
                }
                self.write(json.dumps(ret))
                self.finish()
                return

            user_base = data_user_base_mysql \
                .get_user_base_by_userid(user_third['userid'])

            if not user_base or not user_base['phone']:
                ret = {
                    'idx': self.ss_idx,
                    'ret': 0,
                    'res': {'phone': ''},
                    'msg': '未绑定手机号',
                    }
                self.write(json.dumps(ret))
                self.finish()
                return

        black_userid_list = data_black_user_mysql.get_black_user_all()
        if user_base['userid'] in black_userid_list:
            ret = {
                'idx': self.ss_idx,
                'ret': -4,
                'res': {},
                'msg': '帐号异常',
            }
            self.write(json.dumps(ret))
            self.finish()
            return

        expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)

        login(self, user_base, expires)

        data_user_ss_mysql.update_userid_by_ssid({'ssid': self.ssid, 'userid': self.ss_user['userid']})

        log.i('login now : userid=%s , phone=%s, ssid=%s, imglink=%s' % (self.ss_user['userid'], self.ss_user['phone'], self.ssid, self.ss_user['imglink']))

        res = {
            'idx': self.ss_idx,
            'ret': 0,
            'msg': '欢迎回来',
            'res': {
                'ssid': self.ssid,
                'userid': self.ss_user['userid'],
                # 'email': self.ss_user['email'],
                'phone': self.ss_user['phone'],
                'name': self.ss_user['name'],
                'imglink': self.ss_user['imglink'],
                'thumblink': self.ss_user['imglink'][0:-1] + u'132',
                'intro': self.ss_user['intro'],
                'zone': self.ss_user['zone'],
                'sex': self.ss_user['sex'],
                'sexot': self.ss_user['sexot'],
                'love': self.ss_user['love'],
                'horo': self.ss_user['horo'],
            }
        }
        self.write(json.dumps(res))
        self.finish()
        return


class SignOutHandler(BaseHandler):
    @ApiHost
    def post(self):
        logout(self)
        res = {'idx': self.ss_idx, 'ret': 0, 'msg': '已退出', 'res': {}}
        self.write(json.dumps(res))
        self.finish()


class SignUpHandler(BaseHandler):
    @ApiGuest
    def post(self):
        phone = self.ss_params['phone']
        passwd = self.ss_params['passwd']
        name = self.ss_params['name']
        headurl = self.ss_params['headurl']
        verify = self.ss_params['verify']
        unionid = self.ss_params['unionid']
        from_where = self.ss_params['from']
        log.i('phone=%s , passwd=%s , verify=%s , ssid=%s' % (phone, passwd, verify, self.ssid))
        if not phone:
            log.w('empty phone')
            res = {'idx': self.ss_idx, 'ret': 2, 'msg': '手机号不能为空', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        phone = phone.strip()
        rephone = re.compile(phone_regex)
        if not rephone.match(phone):
            log.w('phone check failed')
            res = {'idx': self.ss_idx, 'ret': 3, 'msg': '手机号格式有误', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        if not check_verify_code(phone, VERIFY_TYPE_REGISTER, verify, False):
            log.i('verify error')
            res = {'idx': self.ss_idx, 'ret': 6, 'msg': '验证码错误', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        if data_user_base_mysql.get_user_base_by_phone(phone):
            log.i('phone has been used')
            res = {'idx': self.ss_idx, 'ret': 4, 'msg': '该手机号已被注册', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return
        user_third = data_user_third_mysql.get_user_third_by_type_and_userkey(
            from_where, unionid,
        )

        if not user_third:
            # 微信未登录过且没有绑定手机号
            userid = mongo.count_userid()
            if not data_user_base_mysql.add_user_base_item({'userid': userid,
                                                            # 'email': '',
                                                            'phone': phone,
                                                            'passwd': passwd}):
                log.e('user base create error')
                res = {'idx': self.ss_idx, 'ret': 6, 'msg': etc.err_500, 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return
            zone = name + '的空间'
            if not data_user_brief_mysql.add_user_brief_item({
                'userid': userid,
                'name': name,
                'intro': '',
                'zone': zone,
                'imglink': headurl,
            }):
                log.e('user brief create error')
                res = {'idx': self.ss_idx, 'ret': 7, 'msg': etc.err_500, 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return
            if not data_user_third_mysql.add_user_third_item({
                'userid': userid,
                'type': from_where,
                'userkey': unionid,
            }):
                log.e('user third create error')
                res = {'idx': self.ss_idx, 'ret': 8, 'msg': etc.err_500, 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return
            if not data_user_detail_mysql.add_user_detail_item({
                'userid': userid,
                'sex': '',
                'sexot': '',
                'love': '',
                'horo': ''
            }):
                log.e('user detail create error')
                res = {'idx': self.ss_idx, 'ret': 9, 'msg': etc.err_500, 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return
        else:
            # 微信登录过且未绑定了手机号
            userid = user_third['userid']
            user_base = data_user_base_mysql.get_user_base_by_userid(userid)
            if not user_base:
                if not data_user_base_mysql.add_user_base_item({
                    'userid': userid,
                    'phone': phone,
                    'passwd': passwd
                }):
                    log.e('user base create error')
                    res = {'idx': self.ss_idx, 'ret': 6, 'msg': etc.err_500, 'res': {}}
                    self.write(json.dumps(res))
                    self.finish()
                    return
            else:
                if not data_user_base_mysql\
                        .update_user_phone_and_password_by_userid(
                    userid, phone, passwd
                ):
                    log.e('user_base update error')
                    res = {'idx': self.ss_idx, 'ret': 6, 'msg': etc.err_500, 'res': {}}
                    self.write(json.dumps(res))
                    self.finish()
                    return

            zone = name + '的空间'
            user_brief = data_user_brief_mysql.get_user_brief_by_userid(userid)
            if not user_brief:
                if not data_user_brief_mysql\
                        .add_user_brief_item({
                    'userid': userid,
                    'name': name,
                    'intro': '',
                    'zone': zone,
                    'imglink': headurl,
                }):
                    log.e('user brief create error')
                    res = {'idx': self.ss_idx, 'ret': 7, 'msg': etc.err_500, 'res': {}}
                    self.write(json.dumps(res))
                    self.finish()
                    return

            user_detail = data_user_detail_mysql\
                .get_user_detail_by_userid(userid)
            if not user_detail:
                if not data_user_detail_mysql.add_user_detail_item({
                    'userid': userid,
                    'sex': '',
                    'sexot': '',
                    'love': '',
                    'horo': ''
                }):
                    log.e('user detail create error')
                    res = {'idx': self.ss_idx, 'ret': 9, 'msg': etc.err_500, 'res': {}}
                    self.write(json.dumps(res))
                    self.finish()
                    return

        log.i('new user base/info created: userid=%s, phone=%s , passwd=%s' % (userid, phone, passwd))

        del_verify_code(phone, VERIFY_TYPE_REGISTER, verify)

        expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
        domain = util.get_domain_from_host(self.request.host)
        self.ss_user = {
            'ssid': self.ssid,
            'userid': userid,
            # 'email': '',
            'phone': phone,
            'name': name,
            'sex': -1,
            'intro': '',
        }
        self.ssid_hmac = session_base.generate_hmac(self.ssid)
        self.set_secure_cookie(etc.cookie_check, self.ssid, domain=domain, expires=expires)
        self.set_secure_cookie(etc.cookie_verify, self.ssid_hmac, domain=domain, expires=expires)
        self.ss_store.set(self.ssid, self.ss_user)
        data_user_ss_mysql.update_userid_by_ssid({'ssid': self.ssid, 'userid': self.ss_user['userid']})

        log.i('login now : userid=%s , ssid=%s' % (self.ss_user['userid'], self.ssid))
        res = {
            'idx': self.ss_idx,
            'ret': 0,
            'msg': '已注册并登录',
            'res': {
                "userid": userid,
                "phone": phone,
                "name": name,
                "intro": "",
                "zone": zone,
                "sex": "",
                "sexot": "",
                "love": "",
                "horo": "",
            }
        }
        self.write(json.dumps(res))
        self.finish()
        return

class ValidateHandler(BaseHandler):
    @ApiHost
    def post(self, *args, **kwargs):
        log.i('============ss_idx=%d===========' % self.ss_idx)
        res = {'idx': self.ss_idx, 'ret': 0, 'msg': '登录成功', 'res': {}}
        self.write(json.dumps(res))
        self.finish()
        return

class FindPwdVerifyHandler(BaseHandler):
    @ApiGuest
    def post(self):
        try:
            phone = self.ss_params.get('phone', None)
            verify = self.ss_params.get('verify', None)

            phone = phone.strip()

            log.i('phone=%s, verify=%s' % (phone, verify))
            if self.generate_res(phone, 2, '手机号不能为空', 'empty phone'):
                return
            if self.generate_res(verify, 3, '验证码不能为空', 'empty verify'):
                return

            rephone = re.compile(phone_regex)
            if self.generate_res(rephone.match(phone), 4, '手机号格式有误', 'phone verify failed'):
                return
            # domain = util.get_domain_from_host(self.request.host)
            if self.generate_res(data_user_base_mysql.get_user_base_by_phone(phone),
                                 7, '该手机号还没有注册', 'phone does not exit'):
                return
            if self.generate_res(check_verify_code(phone, VERIFY_TYPE_FIND, verify, False), 5, '验证码错误',
                                 'verify code error'):
                return

            log.w('find_pwd success')
            ret = {
                'idx': self.ss_idx,
                'ret': 0,
                'res': {},
                'msg': '找回密码成功'
            }
            self.write(json.dumps(ret))
            self.finish()
            return
        except Exception as e:
            log.exp(e)
            res = {
                'idx': self.ss_idx,
                'ret': 1,
                'res': {},
                'msg': '找回密码失败'
            }
            self.write(json.dumps(res))
            self.finish()
            return

class ResetPwdHandler(BaseHandler):
    @ApiGuest
    def post(self):
        try:
            phone = self.ss_params.get('phone', None)
            verify = self.ss_params.get('verify', None)
            passwd = self.ss_params.get('passwd', None)
            repasswd = self.ss_params.get('repasswd', None)

            phone = phone.strip()

            log.i('phone=%s, verify=%s, pwd=%s, repwd=%s'
                  % (phone, verify, passwd, repasswd))
            if self.generate_res(phone, 2, '手机号不能为空', 'empty phone'):
                return
            if self.generate_res(verify, 3, '验证码不能为空', 'empty verify'):
                return
            if self.generate_res(passwd, 4, '密码不能为空', 'empty passwd'):
                return
            if self.generate_res(repasswd, 5, '重复密码不能为空', 'empty repasswd'):
                return

            rephone = re.compile(phone_regex)
            if self.generate_res(rephone.match(phone),
                                     6, '手机号格式有误', 'phone verify failed'):
                return
            # domain = util.get_domain_from_host(self.request.host)
            if self.generate_res(data_user_base_mysql.get_user_base_by_phone(phone),
                                 7, '该手机号还没有注册', 'phone does not exit'):
                return
            if self.generate_res(passwd == repasswd, 8, '两次输入密码不一致', 'two passwd not same'):
                return

            if self.generate_res(check_verify_code(phone, VERIFY_TYPE_FIND, verify, True), 9, '验证码错误', 'verify code error'):
                return

            if data_user_base_mysql.update_passwd_by_phone(phone, passwd):
                log.w('reset_pwd success')
                ret = {
                    'idx': self.ss_idx,
                    'ret': 0,
                    'res': {},
                    'msg': '重置密码成功'
                }
                self.write(json.dumps(ret))
                self.finish()
                return

            else:
                self._generate_res(10, '重置密码失败', 'reset_pwd fail')
                return

                # vid = util.make_a_secret()
                # vid = vid.replace( "+", "" )
                # vid = vid.replace( '=', "" ) #去掉 + = 号避免get请求编码错误

                # reset = data_user_base_mysql.create_reset( mongo.db_pool[domain].reset, phone, vid )
                # if not reset:
                #     log.e( 'reset_pwd create error')
                #     res = { 'op': False, 'msg': etc.err_500}
                #     self.write( json.dumps(res) )
                #     self.finish()
                #     return
                # log.i( 'new reset_pwd created: vid=%s email=%s' % (str(vid), phone) )
                # mail = admin.send_mail(phone, '重置密码', vid)
                # if not mail:
                #     log.w('send mail failure')
                #     reset = data_user_base_mysql.del_reset( mongo.db_pool[domain].reset, email )
                #     res = { 'op':True, 'msg':'发送邮件失败，请重新尝试' }
                #     self.write(json.dumps(res))
                #     self.finish()
                #     return
                # else:
                #     log.i('send mail success')
                #     res = { 'op':True, 'msg':'找回密码已经发送到您的邮箱，请查收' }
                #     self.write( json.dumps(res) )
                #     self.finish()
                #     return
        except Exception as e:
            log.exp(e)
            res = {
                'idx': self.ss_idx,
                'ret': 1,
                'res': {},
                'msg': '重置密码错误'
            }
            self.write(json.dumps(res))
            self.finish()
            return


# class EmailEditHandler(BaseHandler):
#     @ApiGuest
#     def post(self):
#         try:
#             new_email = self.get_argument('new_email', default=None)
#             log.i('email=%s' % new_email)
#             if not new_email:
#                 log.w('empty email')
#                 res = {'op': False, 'msg': '邮箱不能为空'}
#                 log.i('email=%s' % new_email)
#                 self.write(json.dumps(res))
#                 self.finish()
#                 return
#             email = new_email.strip().lower()
#             remail = re.compile(mail_regex)
#             if not remail.match(email):
#                 log.w('email verify failed')
#                 res = {'op': False, 'msg': '邮箱格式有误'}
#                 self.write(json.dumps(res))
#                 self.finish()
#                 return
#             domain = util.get_domain_from_host(self.request.host)
#             userid = self.ss_user['userid']
#             res = data_user_base_mysql.update_user_by_id(mongo.db_pool[domain].user, userid, None, email, None)
#             if not res:
#                 log.e('update email by userid error')
#                 res = {'op': False, 'msg': etc.err_500}
#                 self.write(json.dumps(res))
#                 self.finish()
#                 return
#             log.i('update email by userid success')
#             res = {'op': True, 'msg': "修改邮箱成功"}
#             self.write(json.dumps(res))
#             self.finish()
#             return
#         except Exception as e:
#             log.exp(e)
#             res = {'op': False, 'msg': etc.err_500}
#             self.write(json.dumps(res))
#             self.finish()
#             return


class PwdEditHandler(BaseHandler):
    @ApiGuest
    def post(self):
        try:
            old_pwd = self.get_argument('old_pwd', default=None)
            new_pwd = self.get_argument('new_pwd', default=None)
            log.i('old pwd=%s, new pwd = ' % (old_pwd, new_pwd))
            if not new_pwd or not old_pwd:
                log.w('empty new_pwd or old_pwd')
                res = {'op': False, 'msg': '密码不能为空'}
                log.i('old pwd=%s, new pwd = ' % (old_pwd, new_pwd))
                self.write(json.dumps(res))
                self.finish()
                return
            domain = util.get_domain_from_host(self.request.host)
            userid = self.ss_user['userid']
            res = data_user_base_mysql.update_user_by_id(mongo.db_pool[domain].user, userid, new_pwd, None, None)
            if not res:
                log.e('update password by userid error')
                res = {'op': False, 'msg': etc.err_500}
                self.write(json.dumps(res))
                self.finish()
                return
            log.i('update password by userid success')
            res = {'op': True, 'msg': "修改密码成功"}
            self.write(json.dumps(res))
            self.finish()
            return
        except Exception as e:
            log.exp(e)
            res = {'op': False, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return


# '''
# upload user's head
# '''
# class HeadUploadHandler(tornado.web.RequestHandler):
#     def post(self) :
#         try :
#             meta = self.request.files['file']
#             userid = self.get_argument( 'userid' )
#
#             if not (userid and meta) :
#                 log.w('params fetching error')
#                 return
#
#             # { "ret" : 0, "msg" : "ok", "res" : dst_res }
#             res = file_util.img_file_upload(meta)
#             if res['ret'] == 0 and res['res']:
#                 dst_res = res['res']
#                 item = {}
#                 item['userid']=int( userid )
#                 item['imgid']=dst_res['imgid']
#                 data_user_head_mysql.add_user_head_item( item )
#                 data_user_info_mysql.update_head_by_userid( int( userid ), dst_res['imgid'] )
#
#             return
#         except Exception as e :
#             log.exp(e)
#             log.e('userid=' + userid + ' head upload failure')
#             #res = { 'idx':0, 'ret':1, 'msg':'ng', 'res':[] }
#             #self.write( json.dumps(res) )
#             #self.finish()
#             return
#
# '''
# get user's head
# '''
# class GetUserHandler(tornado.web.RequestHandler):
#     @ApiGuest
#     def post( self ) :
#         try :
#             userid = self.get_argument( 'userid', default=None )
#             if not userid :
#                 log.w('params fetching error')
#                 res = { 'idx':self.ss_idx, 'ret':1, 'msg':'用户ID不能为空', 'res':{} }
#                 self.write( json.dumps(res) )
#                 self.finish()
#                 return
#
#             # { "ret" : 0, "msg" : "ok", "res" : dst_res }
#             user_dict = data_user_info_mysql.get_user_info_by_userid( int(userid) )
#             user_dict['head'] = ''
#             if user_dict['imgid'] != 0 :
#                 head_dict = data_img_base_mysql.get_img_base_by_imgid( user_dict['imgid'] )
#                 if head_dict :
#                     user_dict['head'] = 'http://static.shitouren.com/group'+str(head_dict['group'])+'/'+head_dict['path']+'.'+head_dict['ext']
#
#             res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':user_dict }
#             log.i ( res )
#             self.write( json.dumps(res) )
#             self.finish()
#             return
#         except Exception as e :
#             log.exp(e)
#             res = { 'op':False, 'msg':etc.err_500 }
#             self.write( json.dumps(res) )
#             self.finish()
#             return

class GetUserHandler(BaseHandler):
    @ApiGuest
    def post(self):
        try:
            userid = self.ss_params['userid']
            if userid is None:
                log.w('params fetching error')
                res = { 'idx':self.ss_idx, 'ret':1, 'msg':'用户ID不能为空', 'res':{} }
                self.write( json.dumps(res) )
                self.finish()
                return
            user_brief = data_user_brief_mysql.get_user_brief_by_userid(userid)
            user_detail = data_user_detail_mysql.get_user_detail_by_userid(userid)
            user_info = {
                'userid': userid,
                'name': user_brief['name'],
                'intro': user_brief['intro'],
                'zone': user_brief['zone'],
                'imglink': user_brief['imglink'],
                'thumblink': user_brief['imglink'][0:-1] + u'132',
                'sex': user_detail['sex'] if user_detail else '',
                'sexot': user_detail['sexot'] if user_detail else '',
                'love': user_detail['love'] if user_detail else '',
                'horo': user_detail['horo'] if user_detail else ''
            }
            res = {'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': user_info}
            log.i (res)
            self.write(json.dumps(res))
            self.finish()
            return
        except Exception as e :
            log.exp(e)
            res = {'op':False, 'msg':etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return

class MyPostNotesHandler(BaseHandler):
    @ApiHost
    def post(self):
        try:
            prov_id = self.params["provid"]
            note_list = data_topic_note_mysql \
                .get_topic_note_by_provid_and_userid(prov_id, self.ss_user['userid'])
            if note_list is None:
                log.w('mynotes query error')
                res = {'idx': self.ss_idx, 'ret': 1, 'msg': '获取错误', 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return

            res = {'idx': self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': note_list}
            log.i(res)
            self.write(json.dumps(res))
            self.finish()
        except Exception as e:
            log.exp(e)
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': '获取错误', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return


class MyLikeNotesHandler(BaseHandler):
    @ApiHost
    def post(self):
        try:
            provid = self.params.get("provid")
            if not provid:
                log.w('params fetching error')
                res = {'idx': self.ss_idx, 'ret': 1, 'msg': 'prov不能为空', 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return

            note_id_list = data_topic_note_like_mysql \
                .get_like_topic_note_id_by_userid(self.ss_user['userid'])
            if note_id_list is None:
                log.w('mylikenoteid query error')
                res = {'idx': self.ss_idx, 'ret': 1, 'msg': '获取错误', 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return

            if note_id_list is []:
                note_list = []
            else:
                note_list = data_topic_note_mysql \
                    .get_topic_note_by_provid_and_noteidlist(provid, note_id_list)
                if note_id_list is None:
                    log.w('mylikenotes query error')
                    res = {'idx': self.ss_idx, 'ret': 1, 'msg': '获取错误', 'res': {}}
                    self.write(json.dumps(res))
                    self.finish()
                    return

            res = {'idx': self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': note_list}
            log.i(res)
            self.write(json.dumps(res))
            self.finish()
        except Exception as e:
            log.exp(e)
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': '获取错误', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

class UpdateUserDetailHandler(BaseHandler):
    @ApiHost
    def post(self, *args, **kwargs):
        try:
            userid = self.current_user.get('userid', '')
            sex = self.ss_params.get('sex', '')
            sexot = self.ss_params.get('sexot', '')
            love = self.ss_params.get('love', '')
            horo = self.ss_params.get('horo', '')

            if userid is None:
                log.w('params fetching error')
                res = { 'idx':self.ss_idx, 'ret':1, 'msg':'未登录', 'res':{} }
                self.write( json.dumps(res) )
                self.finish()
                return

            sex_options = ['男生', '女生', '性别自由切换', '内心是女生', '内心是男生', \
                           '现在是女生啦', '现在是男生啦', '尚未明确的性别', '保密', '男', '女', '']
            sexot_options = ['异性恋', '同志', '女女', '性别无关之爱', '无欲望者', '二禁恋(只爱二次元)', \
                             '唯物主义', '宠物恋', '绝对自恋', '男', '女', '双性恋', '不确定', '']
            love_options = ['单身待解救', '疯狂找对象', '疗伤中勿扰', '备胎收集癖', '备胎等上位', '墙角有点松', \
                            '不虐狗难受', '你管得着吗', '我是处女座', '单身', '非单身', '保密', '']
            horo_options = ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座',  \
                            '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座', '']

            if (sex not in sex_options) \
                or (sexot not in sexot_options) \
                or (love not in love_options) \
                or (horo not in horo_options):
                log.w('params fetching error')
                res = { 'idx':self.ss_idx, 'ret':1, 'msg':'参数错误', 'res':{} }
                self.write( json.dumps(res) )
                self.finish()
                return

            item = data_user_detail_mysql.update_user_detail_by_userid(userid, sex, sexot, love, horo)

            if item is True:
                res = {'idx': self.ss_idx, 'ret': 0, 'msg': '更新成功', 'res': {}}
                log.i(res)
                self.write(json.dumps(res))
                self.finish()
        except Exception as e:
            log.exp(e)
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': '更新失败', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

class UpdateUserBriefHandler(BaseHandler):
    @ApiHost
    def post(self, *args, **kwargs):
        try:
            userid = self.current_user.get('userid', '')
            intro = self.ss_params.get('intro', '')
            zone = self.ss_params.get('zone', '')

            if userid is None:
                log.w('params fetching error')
                res = { 'idx':self.ss_idx, 'ret':1, 'msg':'未登录', 'res':{} }
                self.write( json.dumps(res) )
                self.finish()
                return

            item = data_user_brief_mysql.update_user_brief_by_userid(userid, intro, zone)

            if item is True:
                result = data_user_brief_mysql.get_user_brief_by_userid(userid)
                res = {'idx': self.ss_idx, 'ret': 0, 'msg': '更新成功', 'res': result}
                log.i(res)
                self.write(json.dumps(res))
                self.finish()
        except Exception as e:
            log.exp(e)
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': '更新失败', 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

class ApiNotFoundHandler(BaseHandler):
    def get(self):
        raise tornado.web.HTTPError(503)

    @tornado.web.asynchronous
    def post(self):
        log.i('503')
        res = {'idx': -1, 'ret': -5, 'msg': etc.err_no_api, 'res': {}}
        self.write(json.dumps(res))
        self.finish()